/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package reportcenter.report.support.exporter;

import ar.com.fdvs.dj.core.DJConstants;
import ar.com.fdvs.dj.core.DynamicJasperHelper;
import ar.com.fdvs.dj.core.layout.ClassicLayoutManager;
import ar.com.fdvs.dj.domain.ColumnsGroupVariableOperation;
import ar.com.fdvs.dj.domain.DynamicReport;
import ar.com.fdvs.dj.domain.Style;
import ar.com.fdvs.dj.domain.builders.ColumnBuilder;
import ar.com.fdvs.dj.domain.builders.DynamicReportBuilder;
import ar.com.fdvs.dj.domain.builders.GroupBuilder;
import ar.com.fdvs.dj.domain.constants.Border;
import ar.com.fdvs.dj.domain.constants.Font;
import ar.com.fdvs.dj.domain.constants.GroupLayout;
import ar.com.fdvs.dj.domain.constants.HorizontalAlign;
import ar.com.fdvs.dj.domain.constants.Transparency;
import ar.com.fdvs.dj.domain.constants.VerticalAlign;
import ar.com.fdvs.dj.domain.entities.ColumnsGroup;
import ar.com.fdvs.dj.domain.entities.columns.AbstractColumn;
import ar.com.fdvs.dj.domain.entities.columns.PropertyColumn;
import java.awt.Color;
import java.io.File;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.export.JRXlsExporter;
import net.sf.jasperreports.engine.export.JRXlsExporterParameter;
import org.openide.util.Exceptions;
import org.springframework.richclient.util.EventListenerListHelper;
import reportcenter.report.dominio.column.ReportColum;
import reportcenter.report.dominio.footer.ColumFooter;
import reportcenter.report.support.ReportManager;
import reportcenter.report.support.query.QueryInterceptor;
import reportcenter.support.dbutil.ConnectionManager;
import reportcenter.support.resourceload.DataSourceConfig;
import reportcenter.support.sorting.CollectionSorting;

/**
 *
 * @author renan
 */
public class XlsExporter implements ReportExporter {
    
    private EventListenerListHelper listeners = null;
    
    public XlsExporter(EventListenerListHelper listeners){
        this.listeners = listeners;
    }
    
//    private Style header
    public boolean export(ReportManager rM) {
        listeners.fire("progress", new Integer(15));
        Connection conn = null;
        boolean retorno = false;
        try {
            new ConnectionManager(new DataSourceConfig(rM.REPORT.getIdD()));
            conn = ConnectionManager.ds.getConnection();

            //Definir ESTILO

            Style headerStyle = new Style();
            headerStyle.setFont(Font.VERDANA_MEDIUM_BOLD);
            headerStyle.setBorderBottom(Border.PEN_2_POINT);
            headerStyle.setHorizontalAlign(HorizontalAlign.CENTER);
            headerStyle.setVerticalAlign(VerticalAlign.MIDDLE);
            headerStyle.setBackgroundColor(Color.DARK_GRAY);
            headerStyle.setTextColor(Color.WHITE);
            headerStyle.setTransparency(Transparency.OPAQUE);
            headerStyle.setStretchWithOverflow(Boolean.TRUE);
            
            Style headerFooterStyle = new Style();
            headerFooterStyle.setFont(Font.VERDANA_MEDIUM_BOLD);
            headerFooterStyle.setBorderBottom(Border.PEN_2_POINT);
            headerFooterStyle.setHorizontalAlign(HorizontalAlign.CENTER);
            headerFooterStyle.setVerticalAlign(VerticalAlign.MIDDLE);
            headerFooterStyle.setBackgroundColor(Color.RED);
            headerFooterStyle.setTextColor(Color.WHITE);
            headerFooterStyle.setTransparency(Transparency.OPAQUE);
            headerFooterStyle.setStretchWithOverflow(Boolean.TRUE);

            Style detailStyle = new Style();
            detailStyle.setStretchWithOverflow(Boolean.TRUE);
            
            Style detailFooterStyle = new Style();
            detailFooterStyle.setStretchWithOverflow(Boolean.TRUE);
            
            Style titleStyle = new Style();
            titleStyle.setFont(new Font(16, Font._FONT_VERDANA, true));
            titleStyle.setStretchWithOverflow(Boolean.TRUE);
            titleStyle.setBackgroundColor(Color.GREEN);

            Style oddRowStyle = new Style();
            oddRowStyle.setBorder(Border.NO_BORDER);
            oddRowStyle.setBackgroundColor(Color.LIGHT_GRAY);
            oddRowStyle.setTransparency(Transparency.OPAQUE);



            DynamicReportBuilder drb = new DynamicReportBuilder();
            Integer margin = new Integer(10);
//            drb.addSubtitle(rM.REPORT.getSubtitle()).addTitleStyle(titleStyle) //defines the style of the title
            drb.addSubtitle(null)
                    .addDetailHeight(new Integer(15)) //defines the height for each record of the report
                    .addLeftMargin(margin) //define the margin space for each side (top, bottom, right and left)
                    .addRightMargin(margin).addTopMargin(margin) //
                    .addBottomMargin(margin).addColumnsPerPage(new Integer(1)) //
                    .setPrintBackgroundOnOddRows(true) //
                    .setOddRowBackgroundStyle(oddRowStyle); //
//                    .addFirstPageImageBanner("images/qq_medio.jpg", new Integer(122), new Integer(47), ImageBanner.ALIGN_RIGHT);
//                    .addImageBanner("images/qq_medio.jpg", new Integer(122), new Integer(47), ImageBanner.ALIGN_RIGHT);


            Map<String, AbstractColumn> colunas = new HashMap<String, AbstractColumn>();
            drb.setPrintColumnNames(true);
            //Criar colunas
            
//            //Ordenar de acordo com clausula SELECT do comando SQL
//            //TESTE ORDENACAO COLUNAS DO RELATÓRIO
//            System.out.println("====== SEM METODO DE ORDANECAO ======");
//            for (ReportColum f : rM.REPORT.getReportColumCollection()) {
//                System.out.println("ID_RC - > " + f.getIdRc());
//            }
//            
//            System.out.println("====== COM METODO DE ORDANECAO ======");
//            List<ReportColum> temp = CollectionSorting.ordenarLista((List) rM.REPORT.getReportColumCollection(), "idRc");
//            for (ReportColum f : temp) {
//                System.out.println("ID_RC - > " + f.getIdRc());
//            }
            
            List<ReportColum> temp = CollectionSorting.ordenarLista((List) rM.REPORT.getReportColumCollection(), "columnPosition");
//            for (ReportColum f : rM.REPORT.getReportColumCollection()) {
            for (ReportColum f : temp) {
                AbstractColumn column = ColumnBuilder.getInstance() //creates a new instance of a ColumnBuilder
                        .addColumnProperty(f.getColumnName(), f.getClazz()) //defines the field of the data source that this column will show, also its type
                        .addTitle(f.getColumnDescr()) //the title for the column
                        .addWidth(f.getWidth()) //the width of the column
                        .addStyle(detailStyle) //defines the style for the records of this column
                        .addHeaderStyle(headerStyle) //defines the style for the title of this column
                        .build();
                

                drb.addColumn(column);

                colunas.put(f.getColumnName(), column);

            }


            //Criar grupos e footers
            for (ReportColum f : rM.REPORT.getReportColumCollection()) {
                //se tem footer entao fazer agrupamento adicionando os footers correspondentes
                if (!f.getColumFooterCollection().isEmpty()) {

                    GroupBuilder gb1 = new GroupBuilder();
                    gb1.addCriteriaColumn((PropertyColumn) colunas.get(f.getColumnName()));//Pega a coluna incluída de acordo com seu nome do Map de colunas incluídas
                    gb1.addGroupLayout(GroupLayout.VALUE_FOR_EACH);

                    //adicionar footers ao agrupamento
                    for (ColumFooter footer : f.getColumFooterCollection()) {
                        AbstractColumn column = colunas.get(footer.getColumnName());
                        column.setHeaderStyle(headerFooterStyle);
//                        column.setStyle(detailFooterStyle);
                        gb1.addFooterVariable(column, ColumnsGroupVariableOperation.SUM);
                    }

                    ColumnsGroup g1 = gb1.build();
                    drb.addGroup(g1);
                }
            }

            drb.setAllowDetailSplit(false);
            drb.setUseFullPageWidth(true);
//            drb.setTitle(rM.REPORT.getTitle());
            drb.setIgnorePagination(Boolean.TRUE);
            
            drb.setQuery(new QueryInterceptor().transformToJasperParameters(rM.REPORT.getQuery(), rM.QUERY_PARAMS), DJConstants.QUERY_LANGUAGE_SQL);
            
            JasperPrint jp = null;
            DynamicReport dr = drb.build();
            
            listeners.fire("progress", new Integer(25));

            jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), conn, rM.QUERY_PARAMS);

            listeners.fire("progress", new Integer(70));
            
            if (jp.getPages().size() > 0) {
                retorno = true;
            }

            if (!new File(rM.TARGET_FILE_PATH).exists()) {
                new File(rM.TARGET_FILE_PATH).mkdirs();
            }
            

            JRXlsExporter exporterXLS = new JRXlsExporter();
            exporterXLS.setParameter(JRXlsExporterParameter.JASPER_PRINT, jp);
            exporterXLS.setParameter(JRXlsExporterParameter.OUTPUT_FILE_NAME, rM.TARGET_FILE_PATH + System.getProperty("file.separator") + rM.TARGET_FILE_NAME);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_DETECT_CELL_TYPE, Boolean.TRUE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            exporterXLS.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            exporterXLS.exportReport();
            listeners.fire("progress", new Integer(100));
        } catch (Exception ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            try {
                conn.close();
            } catch (Exception ex) {
                Exceptions.printStackTrace(ex);
            }
        }
        return retorno;
    }
}
